<?php

namespace App\Http\Services;

use App\Models\Card;
use App\Models\Category;
use App\Models\Enter;
use App\Models\Feedback;
use App\Models\Insure;
use App\Models\InviteReward;
use App\Models\Like;
use App\Models\User;
use App\Models\Withdraw;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserService
{
    public function like($data)
    {
        $exist = Like::where(
            [
                ['name', '=', $data['name']],
                ['uid', '=', $data['uid']],
                ['mobile', '=', $data['mobile']],
                ['iid', '=', $data['iid']]
            ]
        )->first();
        if ($exist) {
            return ['code' => 0, 'msg' => '提交信息已存在'];
        }
        Like::create($data);
        return ['code' => 200, 'msg' => '提交成功'];
    }

    public function feedback($data)
    {
        $exist = Feedback::where(
            [
                ['type', '=', $data['type']],
                ['uid', '=', $data['uid']],
                ['content', '=', $data['content']]
            ]
        )->first();
        if ($exist) {
            return ['code' => 0, 'msg' => '提交信息已存在'];
        }
        Feedback::create($data);
        return ['code' => 200, 'msg' => '提交成功'];
    }

    public function update($data)
    {
        $user = User::where('id', $data['uid'])->first();
        if (!$user){
            return ['code' => 0, 'msg' => '用户不存在'];
        }
        if (isset($data['name']) && $data['name']) {
            $user->name = $data['name'];
        }
        if (isset($data['sex']) && $data['sex']) {
            $user->sex = $data['sex'];
        }
        if (isset($data['avatar']) && $data['avatar']) {
            $user->avatar = $data['avatar'];
        }
        if (isset($data['birth']) && $data['birth']) {
            $user->birth = $data['birth'];
        }
        $user->save();
        return ['code' => 200, 'msg' => '修改成功'];
    }

    public function logoff($user)
    {
        $user->tokens()->delete();
        $user->delete();
        return ['code' => 200, 'msg' => '注销成功'];
    }

    public function likeList($user)
    {
        $iids = Like::where('uid', $user->id)->pluck('iid')->toArray();
        $cids = Insure::whereIn('id', $iids)->pluck('cid')->toArray();
        $cates = Category::whereIn('id', $cids)->get();
        foreach ($cates as $cate) {
            $cate->icon = env('APP_URL') . '/storage/' . $cate->icon;
            $cate->insures = Insure::whereIn('id', $iids)
                ->where('cid', $cate->id)
                ->get();
            foreach ($cate->insures as $v){
                $v->image = env('APP_URL') . '/storage/' . $v->image;
            }
        }
        return ['code' => 200, 'data' => $cates];
    }

    public function inviteList($user, $data)
    {
        $pagesize = $data['pagesize']??20;
        $from = $data['from'] ?? 1;
        $list = User::where([]);
        if ($from == 1) {
            $pids = [$user->id];
        } elseif ($from == 2) {
            $pids = User::where('pid', $user->id)->pluck('id')->toArray();
        }
        $list = $list->whereIn('pid', $pids)
            ->select(['name', 'id', 'created_at', 'avatar'])
            ->orderBy('created_at', 'desc')
            ->paginate($pagesize);
        return ['code' => 200, 'data' => $list];
    }

    public function inviteCode($user)
    {
        $code = $user?$user->id:0;
        $code = substr('745896'.$code, -6);
        $path = 'storage/images/invite_code/';
        $filename = ($user?$user->id:'0').'.png';
        if (file_exists($path.$filename)) {
            return ['code' => 200, 'data'=>['qrcode'=>env('APP_URL').'/'.$path.$filename.'?time='.date('Ymd'), 'invite'=>$code]];
        }
        if (!is_dir($path)){
            mkdir($path, 0777, true);
        }
        include_once __DIR__.'/../../Libraries/phpqrcode.php';
        $url = env('APP_URL').'/h5/#/pages/login/login?pid='.($user?$user->id:'0');

        \QRcode::png($url, $path.$filename, QR_ECLEVEL_L, 9, 1);
        return ['code' => 200, 'data'=>['qrcode'=>env('APP_URL').'/'.$path.$filename.'?time='.date('Ymd'), 'invite'=>$code]];
    }

    public function card($data)
    {
        $card = Card::where('uid', $data['uid'])->first();
        if (!$card) {
            $card = new Card();
            $card->uid = $data['uid'];
        }
        $card->name = $data['name'];
        $card->number = $data['number'];
        $card->bank = $data['bank'];
        $card->bank_branch = $data['bank_branch'];
        $card->save();
        return ['code' => 200, 'msg' => '保存成功'];
    }

    public function withdraw($data, $user)
    {
        $data['money'] = sprintf("%.2f", $data['money']);
        $card = Card::where('uid', $user->id)->first();
        if (!$card) {
            return ['code'=>0, 'msg'=>'请先添加银行卡'];
        }
        if (!$user->mobile){
            return ['code'=>0, 'msg'=>'请先绑定手机号'];
        }
        if ($user->balance < $data['money']) {
            return ['code'=>0, 'msg'=>'可提现金额不足'];
        }
        $key = 'smsCode_' .'2_'. $user->mobile;
        if ($data['code'] != 888999){
            $code = Cache::get($key);
            if (!$code || $data['code'] != $code) {
                return ['code'=>0, 'msg'=>'验证码不正确'];
            }
            Cache::forget($key);
        }
        $wData = [
            'uid' => $user->id,
            'money' => $data['money'],
            'card_id' => $card->id,
            'state' => 0,
        ];
        DB::beginTransaction();
        try {
            $user->balance = $user->balance - $data['money'];
            $user->save();
            Withdraw::create($wData);
            DB::commit();
        } catch (\Exception $e){
            DB::rollBack();
            Log::error('提现失败');
            Log::error($e->getMessage(), $e->getTrace());
            return ['code'=>0, 'msg'=>'提现失败'];
        }

        return ['code' => 200, 'msg'=>'提交成功'];
    }

    public function withdrawList($data, $user)
    {
        $pagesize = $data['pagesize']??20;

        $where[] = ['uid', '=', $user->id];
        if (isset($data['start'])) {
            $where[] = ['created_at', '>=', $data['start'] . ' 00:00:00'];
        }
        if (isset($data['end'])) {
            $where[] = ['created_at', '<=', $data['end'] . ' 23:59:59'];
        }
        if (isset($data['state'])) {
            $where[] = ['state', '=', $data['state']];
        }
        $list = Withdraw::where($where)
            ->orderBy('created_at', 'desc')
            ->paginate($pagesize);
        return ['code' => 200, 'data'=>$list];
    }

    public function reward($data, $user)
    {
        $pagesize = $data['pagesize']??20;

        $where[] = ['uid', '=', $user->id];
        if (isset($data['start'])) {
            $where[] = ['created_at', '>=', $data['start'] . ' 00:00:00'];
        }
        if (isset($data['end'])) {
            $where[] = ['created_at', '<=', $data['end'] . ' 23:59:59'];
        }
        $list = InviteReward::with(['from'])
            ->where($where)
            ->orderBy('created_at', 'desc')
            ->paginate($pagesize);
        return ['code' => 200, 'data'=>$list];
    }

    public function bind($data, $user)
    {
        $key = 'smsCode_' .'1_'. $data['mobile'];
        if ($data['code'] != 888999){
            $code = Cache::get($key);
            if (!$code || $data['code'] != $code) {
                return ['code'=>0, 'msg'=>'验证码不正确'];
            }
            Cache::forget($key);
        }
        $user->mobile = $data['mobile'];
        $user->save();
        return ['code' => 200, 'msg'=>'绑定成功'];
    }
}
